package svgedit.gui.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import svgedit.gui.Frame;
import svgedit.gui.PDFFileFilter;

/**
 * Shows discard changes dialog, then sets the document to a new, empty
 * document.
 */
@SuppressWarnings("serial")
public class ExportPDFAction extends AbstractAction
{
    
    private Frame frame;
    
    /** Create this action for the given frame */
    public ExportPDFAction(Frame frame)
    {
        super("Export as PDF");
        this.frame = frame;
    }
    
    public void actionPerformed(ActionEvent ae)
    {
        File file = frame.getDocument().getFile();
        JFileChooser dialog;
        if (file != null)
            dialog = new JFileChooser(file);
        else
            dialog = new JFileChooser(frame.getPreferences().getDefaultPath());
        dialog.addChoosableFileFilter(new PDFFileFilter());
        
        dialog.showSaveDialog(null);
        
        file = dialog.getSelectedFile();
        if (file != null)
        {
            if (file.getPath().toLowerCase().endsWith(".pdf") == false)
                file = new File(file.getPath() + ".pdf");
            
            if (file.exists())
            {
                if (JOptionPane
                        .showConfirmDialog(
                                frame.getRootPane(),
                                String.format(
                                        "Do you want to replace the existing file named %s?",
                                        file.getName()),
                                "Overwrite existing file?",
                                JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION)
                    return;
            }
            frame.getPreferences().setDefaultPath(file.getPath());
            frame.exportPDF(file);
        }
        
    }
    
    public void setText(String Text)
    {
        setText(Text);
    }
    
}
